/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.payment.controller;

import cn.hutool.core.util.StrUtil;
import com.icinfo.cloud.common.core.page.PageResponse;
import cn.hutool.core.util.ObjectUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainDetailInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentBillQueryDto;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentMainRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentSlipNumberSaveDto;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentItemDetail;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentMainRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentItemDetailService;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentBillListVo;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentBillTradeWayVo;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentMainRecordVo;
import com.icinfo.cloud.provider.punish.ucase.punishdecide.service.IPunishDecideService;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.web.BaseController;
import com.icinfo.framework.mybatis.mapper.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述:  case_payment_main_record 对应的Controller类.<br>
 *
 * @author framework generator
 * @date 2022年03月01日
 */
@RestController
@RequestMapping("/punish/ucase/payment/record")
@Slf4j
    public class CasePaymentMainRecordController extends BaseController {
    @Resource
    private ICasePaymentMainRecordService casePaymentMainRecordService;
    @Resource
    private IPunishDecideService punishDecideService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICasePaymentItemDetailService casePaymentItemDetailService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    /**
     * 【V1.0.0】描述：查询缴款单信息
     *
     * @param queryDto {@link CasePaymentMainRecordQueryDto}
     * @return {@link Result<List<CasePaymentMainRecordVo>>} 缴款单信息
     * @author xiangyuyu
     * @date 2022-03-01 16:51
     */
    @PostMapping("/getPaymentChannelConfigInfo")
    @ApiOperation(value = "【V1.0.0】描述：查询缴款单信息", httpMethod = "POST")
    public Result<List<CasePaymentMainRecordVo>> getPaymentChannelConfigInfo(@RequestBody @Validated CasePaymentMainRecordQueryDto queryDto) {
        List<CasePaymentMainRecordVo> list = casePaymentMainRecordService.getPaymentChannelConfigInfo(queryDto);
        /*if(list.size()>0) {
            queryDto.setCaseId(list.get(0).getCaseId());
            zljMoney(queryDto);

        }*/
        return Result.success(Constant.STRING_GET_SUCCESS, list);
    }

    /**
     * 【V1.0.0】描述：查询缴款单信息
     *
     * @param saveDto 保存dto
     * @return {@link Result<Map<String, String>> }
     * @author shishengyao
     * @date 2022/09/26
     */
    @PostMapping("/saveCasePaymentMainRecord")
    @ApiOperation(value = "【V1.0.0】描述：查询缴款单信息", httpMethod = "POST")
    public Result<Map<String, String> > saveCasePaymentMainRecord(@RequestBody @Validated CasePaymentSlipNumberSaveDto saveDto) {
         Map<String, Object> paramMap = new HashMap<>();
        //生成缴款单信息
        String paymentSlipNumber = casePaymentMainRecordService.saveCasePaymentMainRecord(saveDto.getCaseId(), saveDto.getDocumentCatalogCode(), saveDto.getPartyId(), saveDto.getCaseType());
        if (!ObjectUtils.isEmpty(paymentSlipNumber)) {
            //获取缴款单二维码信息等
            Map<String, String> paymentInfo = punishDecideService.getPaymentInfo(paymentSlipNumber);
            if (ObjectUtil.isNotEmpty(paymentInfo)){
                paramMap.put("qrBase64", paymentInfo.get("qrBase64"));
                paramMap.put("qrUrl", paymentInfo.get("qrUrl"));
                paramMap.put("XZCFJDS_JKDH", paymentSlipNumber);
                return Result.success(Constant.STRING_GET_SUCCESS, paymentInfo);
            }
        }
        return Result.error(Constant.STRING_GET_FAIL);

    }

    /**
     * 【V1.0.0】缴款单列表查询
     *
     * @param queryDto {@link CasePaymentBillQueryDto}
     * @return {@link Result<PageResponse<CasePaymentBillListVo>>}
     */
    @PostMapping("/queryPaymentBillPageList")
    public Result<PageResponse<CasePaymentBillListVo>> queryPaymentBillPageList(@RequestBody @Validated CasePaymentBillQueryDto queryDto) {
        List<CasePaymentBillListVo> list = casePaymentMainRecordService.queryPaymentBillPageList(queryDto);
        return Result.success(Constant.STRING_GET_SUCCESS, new PageResponse<>(list));
    }

    /**
     * 【V1.10.2】描述： 缴款单列表导出
     *
     * @author: zhengqiang
     * @date: 2023/1/10
     * @param: queryDto
     * @param: response
     * @return
     **/
    @PostMapping("/exportPaymentBillList")
    public void exportPaymentBillList(@RequestBody CasePaymentBillQueryDto queryDto, HttpServletResponse response) throws Exception {
        casePaymentMainRecordService.exportPaymentBillList(queryDto, response);
    }

    /**
     * 缴款单查询支付方式和支付机构列表
     *
     * @return {@link Result<CasePaymentBillTradeWayVo>}
     */
    @GetMapping("/queryPaymentBillTradeWayList")
    public Result<CasePaymentBillTradeWayVo> queryPaymentBillTradeWayList() {
        System.out.println();
        return Result.success(Constant.STRING_GET_SUCCESS, casePaymentMainRecordService.queryPaymentBillTradeWayList());

    }

    /**
     * 专题查询-缴款单查询-查询当地财政部门是否开出发票
     */
    @GetMapping("/getElectricInvoiceByNoticeNo")
    public Result<List<String>> getElectricInvoiceByNoticeNo(@RequestParam("noticeNo") String noticeNo) {
        if(StrUtil.isEmpty(noticeNo)){
            return Result.error("缺少缴款单号参数");
        }
        List<String> list = casePaymentMainRecordService.getElectricInvoiceByNoticeNo(noticeNo);
        if(!ObjectUtil.isEmpty(list) && list.size() > 0){
            return Result.success("发票已开出，本系统将定时（6点,12点,18点,23点）获取发票生成执行情况核查记录，请耐心等待。", list);
        } else {
            return Result.success("电子发票未生成，请咨询当地财政部门确认发票是否开出");
        }
    }

    /**
     * 获取滞纳金
     * @return {@link Result<CasePaymentBillTradeWayVo>}
     */
    @GetMapping("/getZljMoney")
    public Result<Integer> getZljMoney(@RequestBody @Validated CasePaymentMainRecordQueryDto saveDto) {
        int res = zljMoney(saveDto);
        return Result.success(res);
    }
    /**
     *  是否加罚款计算滞纳金
     *
     * @return {@link Result<CasePaymentBillTradeWayVo>}
     */
    private int zljMoney(CasePaymentMainRecordQueryDto saveDto){
        int monery = 0;
        try {
            CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(saveDto.getCaseId());
            System.out.println("caseMainInfoVo******[案件基本信息==滞纳金]");
            if(!ObjectUtils.isEmpty(caseMainInfoVo)){
                SysDepartParam departParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfoVo.getCaseOrgCode(),null);
                System.out.println("departParam*****[部门信息==滞纳金]"+departParam);
                if(!ObjectUtils.isEmpty(departParam)){
                    if(Constant.WHETHER_STRING_YES.equals(departParam.getIsLateFee())){
                        CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
                        queryDto.setCaseId(saveDto.getCaseId());
                        queryDto.setDocumentKindCode(Constant.STRING_KIND_CODE_CFJDS);
                        queryDto.setIsQueryDocumentApprovalTimeNotNull(YesOrNoEnum.YES.getCode());
                        List<CaseDocumentRecordVo>  documentRecordList= caseDocumentRecordService.getCaseDocumentRecordList(queryDto);
                        System.out.println("documentRecordList[*****处罚决定书==滞纳金]"+documentRecordList);
                        if(!ObjectUtils.isEmpty(documentRecordList)){
                            for(CaseDocumentRecordVo documentRecordVo:documentRecordList) {
                                int day = DateUtil.getBetweenDays(DateUtil.formatLocalDateTimeString1(documentRecordVo.getSentTime()), DateUtil.getCurrentTime());
                                System.out.println("有多少天[day*****]="+day);
                                if (day > 15) {
                                    int addDay = day - 15;
                                    CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailInfoByCaseId(saveDto.getCaseId());
                                    if(!ObjectUtils.isEmpty(caseMainDetailInfo)) {
                                        if(StringUtil.isEmpty(caseMainDetailInfo.getDraftPunishMoney())){
                                            continue;
                                        }
                                        int draftPunishMoney = Integer.parseInt(caseMainDetailInfo.getDraftPunishMoney());
                                        monery = (draftPunishMoney * addDay * 3) / 100;
                                        System.out.println("滞纳金*****************[monery]="+monery);
                                        if (monery > draftPunishMoney) {
                                            monery = draftPunishMoney;
                                        }
                                        CasePaymentMainRecord mainRecord = casePaymentMainRecordService.getCasePaymentMainRecord(saveDto.getCaseId(), saveDto.getNoticeNo());
                                        if (!ObjectUtils.isEmpty(mainRecord)) {
                                            mainRecord.setTotalMoney(String.valueOf(draftPunishMoney + monery));
                                            mainRecord.setOverduePayment(String.valueOf(monery));
                                            mainRecord.setOverdueTime(DateUtil.getCurrLocalDateTime());
                                            System.out.println("我是*****************[OverduePayment]="+monery);
                                            casePaymentMainRecordService.updateCasePaymentMainRecord(mainRecord);
                                            List<CasePaymentItemDetail> itemDetailList = casePaymentItemDetailService.getCasePaymentItemDetailByPaymentId(mainRecord.getId());
                                            if (!ObjectUtils.isEmpty(itemDetailList)) {
                                                for (CasePaymentItemDetail casePaymentItemDetail : itemDetailList) {
                                                    casePaymentItemDetail.setChMoney(String.valueOf(draftPunishMoney + monery));
                                                    casePaymentItemDetailService.updateCasePaymentItemDetail(casePaymentItemDetail);
                                                }
                                            }else{
                                                log.info("List<CasePaymentItemDetail>合计金额明细不存在！");
                                            }
                                        }else{
                                            log.info("CasePaymentMainRecord合计金额不存在！");
                                        }
                                    }else{
                                        log.info("CaseMainDetailInfo拟处罚金额不存在！");
                                    }
                                }
                            }
                        }else{
                            log.info("List<CaseDocumentRecordVo>处罚决定书不存在！");
                        }
                    }
                }else{
                    log.info("SysDepartParam部门不存在！");
                }
            }else{
                log.info("caseMainInfoVo案件不存在！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("计算滞纳金失败"+e.getMessage());
        }
        return monery;
    }
}
